package com.xiaomaoguai.user.action;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.xiaomaoguai.commom.utils.EnviromentUtils;
import com.xiaomaoguai.user.model.User;
import com.xiaomaoguai.webkit.model.ResponseEntity;
import com.xiaomaoguai.webkit.web.action.BaseAction;

@Controller
@RequestMapping("app/user")
public class UserAction extends BaseAction {

	@Override
	protected String getJspPathPrefix() {
		return null;
	}

	@RequestMapping(value = "test/{hh}.xhtml", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public ResponseEntity<User> toUserList(@PathVariable("hh") String hh) {
		User user = new User();
		user.setPassword(hh);
		user.setUserId(5);
		ResponseEntity<User> response = new ResponseEntity<User>();
		response.setCode(1);
		response.setSuccess(true);
		response.setResult(user);
		return response;
	}

	@RequestMapping(value = "/upload.xhtml", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> upload(HttpServletRequest request) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iters = multipartRequest.getFileNames();
			while (iters.hasNext()) {
				List<MultipartFile> files = multipartRequest.getFiles(iters.next());
				for (MultipartFile file : files) {
					if (!file.isEmpty()) {
						String originName = file.getOriginalFilename();
						FileUtils.copyInputStreamToFile(file.getInputStream(), new File(EnviromentUtils.IMG_UPLOAD_PATH
								+ originName));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseEntity<String>(ResponseEntity.MessageState.FAILURE);
		}
		return new ResponseEntity<String>(ResponseEntity.MessageState.SUCCESS);
	}

}
